/* genfile.c : generate alphabetical file for testing */
 
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <stdio.h>
 
static inline
void build_alpha(char *buf)
{
  for (char c = 'a'; c <= 'z'; ++c, ++buf)
    *buf = c;
}
 
static inline
void build_spec_range(char *buf, char start, char end)
{
  if (start <= end)
    for (; start <= end; ++start, ++buf)
      *buf = start;
}
 
/*
 * usage:
 * * no param: out alpha on stdout
 * * first param is the filename (if at least one parameters)
 * * second and third define the interval (both needed)
 */
int main(int ac, char* av[])
{
  int                   fd = STDOUT_FILENO;
  char                 *buf;
 
  if (ac > 1)
    if ( (fd = open(av[1],O_WRONLY|O_CREAT|O_TRUNC, 0666)) == -1 )
      {
        perror(av[0]);
        exit(3);
      }
 
  if (ac > 2)
    {
      char              start, end;
      if (ac < 4)
        {
          write(STDERR_FILENO, av[0], strlen(av[0]));
          write(STDERR_FILENO,": missing parameter\n",20);
          exit(2);
        }
      start = av[2][0];
      end = av[3][0];
      if (end < start)
        {
          write(STDERR_FILENO, av[0], strlen(av[0]));
          write(STDERR_FILENO,": parameters mismatch\n",22);
          exit(2);
        }
      buf = malloc(1 + end - start);
      build_spec_range(buf, start, end);
      write(fd, buf, 1 + end - start);
    }
  else
    {
      buf = malloc(26);
      build_alpha(buf);
      write(fd, buf, 26);
    }
 
  write(fd,"\n",1);
 
  if (ac > 1)
    close(fd);
 
  return 0;
}
